<script lang="ts">
	import type { PlanInfo, PlanItemInfo } from '$lib/api/proto/roadmap_plan_api';
	import { appStore } from '$lib/stores/app.svelte';
	import { userStore } from '$lib/stores/user.svelte';
	import { callApi } from '$lib/utils/call_utils';
	import { Calendar } from '@event-calendar/core';
	import EditorJS from '@editorjs/editorjs';
	import SimpleEditor from '$lib/components/editor/SimpleEditor.svelte';
	import { DatePicker } from '@svelte-plugins/datepicker';
	import moment from 'moment';

	interface Props {
		roadmapId: string;
		plan: PlanInfo;
		clickDateInfo?: Calendar.DateClickInfo;
		planItem?: PlanItemInfo;
		onCancel: () => void;
		onOk: (itemId: string) => void;
	}

	let props: Props = $props();

	let title = $state(props.planItem?.basicInfo?.title ?? '');
	let contentEditor: EditorJS | null = $state(null);

	let isStartTimeOpen = $state(false);
	let startTime = $state(
		props.planItem != undefined
			? Number(props.planItem.basicInfo?.startTime ?? 0)
			: (props.clickDateInfo?.date.valueOf() ?? 0)
	);

	let isEndTimeOpen = $state(false);
	let endTime = $state(
		props.planItem != undefined
			? Number(props.planItem.basicInfo?.endTime ?? 0)
			: (props.clickDateInfo?.date.valueOf() ?? 0) + 3600 * 1000
	);

	async function addPlanItem() {
		if (
			userStore.userSession == null ||
			props.clickDateInfo == undefined ||
			contentEditor == null
		) {
			return;
		}

		const contentData = await contentEditor.save();

		const res = await callApi(
			appStore.roadmapPlanApiClient.addPlanItem({
				sessionId: userStore.userSession,
				roadmapId: props.roadmapId,
				targetMemberUserId: props.plan.memberUserId,
				planId: props.plan.planId,
				basicInfo: {
					title: title,
					content: JSON.stringify(contentData),
					startTime: BigInt(startTime),
					endTime: BigInt(endTime)
				}
			}).response
		);

		props.onOk(res.itemId);
		appStore.addToastMessage({
			level: 'success',
			content: '创建任务成功',
			keepTime: 2000
		});
	}

	async function updatePlanItem() {
		if (userStore.userSession == null || props.planItem == undefined || contentEditor == null) {
			return;
		}

		const contentData = await contentEditor.save();

		await callApi(
			appStore.roadmapPlanApiClient.updatePlanItem({
				sessionId: userStore.userSession,
				roadmapId: props.roadmapId,
				targetMemberUserId: props.plan.memberUserId,
				planId: props.plan.planId,
				itemId: props.planItem.itemId,
				basicInfo: {
					title: title,
					content: JSON.stringify(contentData),
					startTime: BigInt(startTime),
					endTime: BigInt(endTime)
				}
			}).response
		);

		props.onOk(props.planItem.itemId);
		appStore.addToastMessage({
			level: 'success',
			content: '修改任务成功',
			keepTime: 2000
		});
	}
</script>

<dialog class="modal modal-open">
	<div class="modal-box w-[800px] max-w-none">
		<button
			class="btn btn-sm btn-circle btn-ghost absolute right-2 top-2"
			onclick={() => props.onCancel()}>✕</button
		>
		<h3 class="text-lg font-bold">
			{props.planItem == undefined ? '创建成长计划' : '修改成长计划'}
		</h3>
		<div class="max-h-[60vh] overflow-y-auto pr-[10px] flex-col space-y-4 pt-[20px]">
			<label class="label w-full">
				<span class="label w-[80px] text-right inline-block pr-[10px]">任务标题:</span>
				<input type="text" class="input w-full" bind:value={title} />
			</label>
			<label class="label w-full">
				<span class="label w-[80px] text-right inline-block pr-[10px]">开始时间:</span>
				<DatePicker
					theme="plan-item"
					bind:isOpen={isStartTimeOpen}
					bind:startDate={startTime}
					showTimePicker
					startDateTime={moment(startTime).format('HH:mm')}
					enablePastDates
					enableFutureDates
					startOfWeek={1}
					dowLabels={['日', '一', '二', '三', '四', '五', '六']}
					monthLabels={[
						'一月',
						'二月',
						'三月',
						'四月',
						'五月',
						'六月',
						'七月',
						'八月',
						'九月',
						'十月',
						'十一月',
						'十二月'
					]}
					enabledDates={[
						`${moment(Number(props.plan.startTime)).format('MM/DD/YYYY')}:${moment(Number(props.plan.endTime)).format('MM/DD/YYYY')}`
					]}
				>
					<button type="button" class="btn btn-ghost" onclick={() => (isStartTimeOpen = true)}
						>{moment(startTime).format('YYYY-MM-DD HH:mm')}</button
					>
				</DatePicker>
			</label>

			<label class="label w-full">
				<span class="label w-[80px] text-right inline-block pr-[10px]">结束时间:</span>
				<DatePicker
					theme="plan-item"
					bind:isOpen={isEndTimeOpen}
					bind:startDate={endTime}
					showTimePicker
					startDateTime={moment(endTime).format('HH:mm')}
					enablePastDates
					enableFutureDates
					startOfWeek={1}
					dowLabels={['日', '一', '二', '三', '四', '五', '六']}
					monthLabels={[
						'一月',
						'二月',
						'三月',
						'四月',
						'五月',
						'六月',
						'七月',
						'八月',
						'九月',
						'十月',
						'十一月',
						'十二月'
					]}
					enabledDates={[
						`${moment(Number(props.plan.startTime)).format('MM/DD/YYYY')}:${moment(Number(props.plan.endTime)).format('MM/DD/YYYY')}`
					]}
				>
					<button type="button" class="btn btn-ghost" onclick={() => (isEndTimeOpen = true)}
						>{moment(endTime).format('YYYY-MM-DD HH:mm')}</button
					>
				</DatePicker>
			</label>

			<h4 class="text-base font-bold">任务说明</h4>
			<SimpleEditor
				sizeClass="min-h-[300px] border-2 border-base-200 max-h-[300px]"
				data={props.planItem?.basicInfo?.content}
				placeholder="请输入任务说明"
				onInit={(tmpEditor) => (contentEditor = tmpEditor)}
			/>
		</div>
		<div class="modal-action">
			<button class="btn" onclick={() => props.onCancel()}>取消</button>
			<button
				class="btn btn-primary"
				disabled={title.trim() == '' || startTime >= endTime}
				onclick={() => {
					if (props.planItem == undefined) {
						addPlanItem();
					} else {
						updatePlanItem();
					}
				}}>{props.planItem == undefined ? '创建' : '修改'}</button
			>
		</div>
	</div>

	<div class="modal-backdrop">
		<button onclick={() => props.onCancel()}>close</button>
	</div>
</dialog>

<style>
	:global(.datepicker[data-picker-theme='plan-item']) {
		--datepicker-container-background: var(--color-base-100);
		--datepicker-container-border: 1px solid var(--color-base-300);
		--datepicker-container-position: absolute;
		--datepicker-container-box-shadow: none;
		--datepicker-calendar-range-selected-background: var(--color-accent);
		--datepicker-calendar-range-background: var(--color-base-200);
		--datepicker-calendar-range-start-box-shadow: inset -20px 0 0 var(--color-accent);
		--datepicker-calendar-range-end-box-shadow: inset 20px 0 0 var(--color-accent);
		--datepicker-calendar-day-color: var(--color-base-content);
		--datepicker-calendar-day-color-disabled: var(--color-base-300);
		--datepicker-calendar-day-color-hover: var(--color-base-content);
		--datepicker-calendar-day-background-hover: var(--color-base-200);
	}
</style>
